package com.nb.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.nb.dto.MenuSortUpdateDTO;
import com.nb.entity.SysMenuEntity;
import com.nb.result.Result;
import com.nb.service.ISysMenuService;
import com.nb.service.impl.AuthServiceImpl;
import com.nb.vo.UserInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单控制器
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    private static final Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private ISysMenuService menuService;

    /**
     * 创建菜单
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @PostMapping("/create")
    public Result createMenu(@RequestBody SysMenuEntity menu) {
        logger.info("Received menu creation request: {}", menu);

        // 校验菜单名称唯一性
        if (!menuService.checkMenuNameUnique(menu)) {
            logger.warn("Menu name is not unique: {}", menu.getName());
            return Result.error("菜单名称已存在");
        }

        // 校验菜单路径唯一性（仅当路径不为空时校验）
        if (menu.getPath() != null && !menu.getPath().isEmpty() && !menuService.checkMenuPathUnique(menu)) {
            logger.warn("Menu path is not unique: {}", menu.getPath());
            return Result.error("菜单路径已存在");
        }

        // 保存菜单
        boolean result = menuService.createMenu(menu);
        logger.info("Menu creation result: {}", result);

        if (result) {
            Map<String, Object> data = new HashMap<>();
            data.put("menu", menu);
            data.put("message", "创建成功");
            return Result.success(data);
        }

        logger.error("Failed to create menu: {}", menu);
        return Result.error("创建失败");
    }

    /**
     * 更新菜单
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @PutMapping("/update")
    public Result updateMenu(@RequestBody SysMenuEntity menu) {
        logger.info("Received menu update request: {}", menu);

        // 检查菜单是否存在
        if (!menuService.checkMenuExists(menu.getId())) {
            logger.warn("Menu not found, menuId: {}", menu.getId());
            return Result.error("菜单不存在");
        }

        // 校验菜单名称唯一性（排除自己）
        if (!menuService.checkMenuNameUnique(menu)) {
            logger.warn("Menu name is not unique: {}", menu.getName());
            return Result.error("菜单名称已存在");
        }

        // 校验菜单路径唯一性（仅当路径不为空时校验）
        if (menu.getPath() != null && !menu.getPath().isEmpty() && !menuService.checkMenuPathUnique(menu)) {
            logger.warn("Menu path is not unique: {}", menu.getPath());
            return Result.error("菜单路径已存在");
        }

        // 更新菜单
        boolean result = menuService.updateMenu(menu);
        logger.info("Menu update result: {}", result);

        if (result) {
            Map<String, Object> data = new HashMap<>();
            data.put("menuId", menu.getId());
            data.put("message", "更新成功");
            return Result.success(data);
        }

        logger.error("Failed to update menu: {}", menu);
        return Result.error("更新失败");
    }

    /**
     * 删除菜单
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @DeleteMapping("/delete/{menuId}")
    public Result deleteMenu(@PathVariable Long menuId) {
        logger.info("Received menu delete request, menuId: {}", menuId);

        // 检查菜单是否存在
        if (!menuService.checkMenuExists(menuId)) {
            logger.warn("Menu not found, menuId: {}", menuId);
            return Result.error("菜单不存在");
        }

        // 获取菜单信息检查是否为核心菜单
        SysMenuEntity menu = menuService.getById(menuId);
        if ("首页".equals(menu.getName())) {
            logger.warn("Cannot delete system core menu, menuId: {}", menuId);
            return Result.error("系统核心菜单禁止删除");
        }

        // 检查是否存在子菜单
        if (menuService.hasChildMenus(menuId)) {
            logger.warn("Menu has child menus, cannot delete, menuId: {}", menuId);
            return Result.error("存在子菜单，无法删除");
        }

        // 删除菜单
        boolean result = menuService.deleteMenu(menuId);
        logger.info("Menu delete result: {}", result);

        if (result) {
            Map<String, Object> data = new HashMap<>();
            data.put("menuId", menuId);
            data.put("message", "删除成功");
            return Result.success(data);
        }

        logger.error("Failed to delete menu, menuId: {}", menuId);
        return Result.error("删除失败");
    }
    /**
     * 菜单分页查询
     *
     * @param page 页码，默认1
     * @param size 每页数量，默认10
     * @param name 菜单名称模糊查询
     * @param path 路由路径精确查询
     * @return 分页结果
     */
    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10") int size,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String path) {
        logger.info("Received menu list request, page: {}, size: {}, name: {}, path: {}", page, size, name, path);
        if(page<1){
            page=1;
        }
        if(size<1||size>100){
            size=10;
        }
        Page<SysMenuEntity> result=menuService.selectMenuPage(page,size,name,path);
        logger.info("Menu list result: {}", result.getTotalRow());
    return Result.success(result);
    }
    /**
     * 菜单详情查询
     *
     * @param menuId 菜单ID
     * @return 菜单详情
     */
    @GetMapping("/detail/{menuId}")
    public Result detail(@PathVariable Long menuId) {
        logger.info("Received menu detail request, menuId: {}", menuId);

        // 检查菜单是否存在
        if (!menuService.checkMenuExists(menuId)) {
            logger.warn("Menu not found, menuId: {}", menuId);
            return Result.error("菜单不存在");
        }

        // 查询菜单详情
        SysMenuEntity menu = menuService.selectMenuById(menuId);
        if (menu == null) {
            logger.warn("Menu detail not found, menuId: {}", menuId);
            return Result.error("菜单不存在");
        }

        logger.info("Menu detail query result: {}", menu);
        return Result.success(menu);
    }

    @GetMapping("/tree")
    public Result getMenuTree() {
        // 获取所有未删除的菜单
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", 0);
        //获取所有菜单
        List<SysMenuEntity> menuList = menuService.list();
        // 调用AuthService中的静态方法构建菜单树
        List<UserInfoVO.Menu> menuTree = AuthServiceImpl.buildMenuTree(menuList);

        return Result.success(menuTree);
    }
    // 在 MenuController 中添加测试方法
    @GetMapping("/testUpdateMenuSortAndParent")
    public Result testUpdateMenuSortAndParent() {
        MenuSortUpdateDTO updateDTO = new MenuSortUpdateDTO();
        updateDTO.setId(24L);
        updateDTO.setParentId(7L);
        updateDTO.setSort(0);

        return updateMenuSortAndParent(updateDTO);
    }

    @PutMapping("/updatetree")
    public Result updateMenuSortAndParent(@RequestBody MenuSortUpdateDTO updateDTO) {
        logger.info("Received menu sort and parent update request, menuId: {}, parentId: {}, sort: {}",
                updateDTO.getId(), updateDTO.getParentId(), updateDTO.getSort());

        // 校验参数
        if (updateDTO.getId() == null || updateDTO.getId() <= 0) {
            logger.warn("Invalid menuId: {}", updateDTO.getId());
            return Result.error("菜单ID无效");
        }

        // 调用服务更新菜单排序和父菜单
        boolean result = menuService.updateMenuSortAndParent(
                updateDTO.getId(),
                updateDTO.getParentId(),
                updateDTO.getSort()
        );

        if (result) {
            Map<String, Object> data = new HashMap<>();
            data.put("menuId", updateDTO.getId());
            data.put("message", "更新成功");
            return Result.success(data);
        }

        logger.error("Failed to update menu sort and parent, menuId: {}", updateDTO.getId());
        return Result.error("更新失败");
    }

}
